package ovm.gui.menu;

import com.vaadin.ui.MenuBar;
import ovm.gui.actions.menu.AbstractMenuAction;
import ovm.entity.MenuEntity;
import ovm.management.menu.MenuManager;

import java.util.List;

public class MainMenu extends MenuBar {

    protected void generate (MenuItem item, MenuEntity parent) {
        List<MenuEntity> childrenList = MenuManager.getChildren(parent.getId());
        if (childrenList.size() > 0) {
            for (MenuEntity entity : childrenList) {
                MenuItem childItem = item.addItem(entity.getCaption(), null, null);
                generate(childItem, entity);
            }
        } else {
            AbstractMenuAction action = null;
            try {
                action = (AbstractMenuAction) Class.forName("ovm.gui.actions.menu."+parent.getActionClass()).newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IllegalAccessException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (ClassNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            item.setCommand(action);
        }
    }

    protected void build () {
        List<MenuEntity> roots = MenuManager.getChildren(-1);
        for (MenuEntity entity : roots) {
            MenuItem item = this.addItem(entity.getCaption(), null, null);
            generate(item, entity);
        }
    }

    public MainMenu() {
        super();
        build();
    }

}
